package com.example.financialsystem;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.financialsystem.adapter.RecordAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import models.Record;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;

import static com.example.financialsystem.application.MyApplication.getContext;
import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.currentBook;
import static others.Const.currentIdAndNameHashTable;
import static others.Const.currentUserVo;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;
import static utils.GsonUtil.String2ListRecordResponse;

public class FlowActivity extends AppCompatActivity {

    @BindView(R.id.ffff_member)
    Spinner spinnerMember;
    @BindView(R.id.ffff_timeZone)
    Spinner spinnerTimeZone;
    @BindView(R.id.ffff_listView)
    ListView listView;
    @BindView(R.id.ffff_memberChoose)
    LinearLayout LinearMemberChoose;

    private List<String> names = new ArrayList<>();
    private List<String> ids = new ArrayList<>();
    private int timeZone = 0;
    private String currentName;
    private String currentId;
    private String responseData;
    private final static int GET_RECORDS = 1;
    private List<Record> records = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flow);
        ButterKnife.bind(this);

        if (currentBook.getType()==0){
            LinearMemberChoose.setVisibility(View.GONE);
        } else {
            LinearMemberChoose.setVisibility(View.VISIBLE);
            for(Map.Entry<String,String> entry: currentIdAndNameHashTable.entrySet()){
                names.add(entry.getValue());
                ids.add(entry.getKey());
            }
        }

        if (currentBook.getType() == 0){
            currentName = currentUserVo.getUsername();
            currentId = currentUserVo.getId();
        }else {
            currentName = names.get(0);
            currentId = ids.get(0);
        }
        Adapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,names);
        spinnerMember.setAdapter((SpinnerAdapter) adapter);
        spinnerMember.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentName = names.get(position);
                currentId = ids.get(position);
                loadData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerTimeZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                timeZone = position;
                sendRequest();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sendRequest();
    }

    public void sendRequest(){
        String url = "http://" + IP + ":" + PORT + "/portal/record/RecordList.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",currentBook.getId())
                .add("timeZone",timeZone+"")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    Message message = new Message();
                    message.what = GET_RECORDS;
                    handler.sendMessage(message);
                } catch (Exception e){
                    e.printStackTrace();
                    ToastShow("我们可能遭遇了一些麻烦1(FlowActivity)");
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GET_RECORDS:
                    ServerResponse<List<Record>> serverResponse = String2ListRecordResponse(responseData);
                    if (serverResponse.getStatus() == 0){
                        records = serverResponse.getData();
                        if (records.size() == 0){
                            ToastShow("暂无数据");
                        } else {
                            loadData();
                        }
                    }else {
                        ToastShow("我们可能遭遇了一些麻烦2(FlowActivity)");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void loadData(){
        if (currentBook.getType() == 0){
            RecordAdapter adapter = new RecordAdapter(this, R.layout.item_record, records);
            listView.setAdapter(adapter);
        } else {
            List<Record> temp = new ArrayList<>();
            for (int i=0;i<records.size();i++){
                if (records.get(i).getUserid().equals(currentId)){
                    temp.add(records.get(i));
                }
            }
            if (temp.size() == 0){
                ToastShow("暂无数据");
            } else {
                RecordAdapter adapter = new RecordAdapter(this, R.layout.item_record, temp);
                listView.setAdapter(adapter);
            }
        }
    }
}
